import { reactive } from 'vue'
import app from '@/app'
import store from '@/app/store'
import { get, update, del } from '@/api/erp/supplier'

// 初始化
const supplierStore = store()

// 分页
supplierStore.page = reactive({
  current: 1,
  pageSize: 0,
  total: 0,
  showPageSize: false,
  loading: false
})

// 查询类型
supplierStore.where = reactive({ 
  key: 'name', 
  value: '' 
})

// 生成查询数据
supplierStore.getWhere = () => {
  // 查询方式
  const where = { [supplierStore.where.key]: supplierStore.where.value }
  // 合并数据
  return Object.assign(where, supplierStore.getData())
}

supplierStore.get = () => {
  return new Promise((resolve, jeject) => {
    supplierStore.page.loading = true
    get(supplierStore.getWhere()).then(res => {
      supplierStore.setList(res.data)
      // 分页
      supplierStore.page.current = res.current_page
      supplierStore.page.pageSize = res.per_page
      supplierStore.page.total = res.total
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      supplierStore.page.loading = false
    })
  })
}

supplierStore.update = (...arge) => {
  return new Promise((resolve, jeject) => {
    update(...arge).then(res => {
      supplierStore.get()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

supplierStore.del = (...arge) => {
  return new Promise((resolve, jeject) => {
    del(...arge).then(res => {
      supplierStore.get()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 重置请求
supplierStore.reset = page => {
  supplierStore.page.current = page
  supplierStore.getData().page = page

  // 开始加载
  supplierStore.get()
}

export default supplierStore